import CustomInput from '@/components/antd-comp/input/CustomInput'
import { showMessage } from '@/components/antd-comp/message'
import ModalComponent from '@/components/antd-comp/modal/ModalComponent'
import { useBuriedEvent } from '@/util/buried'
import type { GetProp } from 'antd'
import { Checkbox, Empty, Segmented, Spin } from 'antd'
import { useEffect, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { useParams } from 'react-router-dom'
import './css/index.css'

const TagDialog = ({ defoptions, cancel, submit, again, optionsValues, updata }) => {
  const { id } = useParams()
  const { t } = useTranslation()
  const { fileLibBuriedEvent } = useBuriedEvent()
  const title = t('lib.tagSetting') + t('lib.tag')
  /* 选中数据 */
  // checkBox 选中
  const [checkedValues, setcheckedValues] = useState([]) as any
  // checkedLabel 右侧显示
  const [checkedLabel, setcheckedLabel] = useState([]) as any
  // 重新生成loading
  const [tagLoading, settagLoading] = useState(false)

  /* AI推荐 自定义创建 */
  const [customMess, setCustomMess] = useState('')
  const [alignValue, setAlignValue] = useState(t('lib.Recommended_ai'))
  const maxLength = 10
  const [options, setoptions] = useState([])

  useEffect(() => {
    settagLoading(false)
    setoptions(defoptions)
  }, [defoptions])
  useEffect(() => {
    setcheckedLabel(optionsValues)
    setcheckedValues(optionsValues)
  }, [optionsValues])

  /* 选择 */
  const CheckonChange: GetProp<typeof Checkbox.Group, 'onChange'> = checkedValuesChange => {
    if (checkedValuesChange.length > 10) {
      showMessage({
        content: '已达添加数量上限',
        type: 'warning'
      })
      return
    }
    setcheckedValues(checkedValuesChange)
    setcheckedLabel(checkedValuesChange)
  }
  /* 删除 */
  const sliceCheckedValues = (num: number, e: string) => {
    // value
    const valueArr = [...checkedValues]
    valueArr.splice(num, 1)
    setcheckedValues(valueArr)
    // label
    const labelArr = [...checkedLabel]
    labelArr.splice(num, 1)
    setcheckedLabel(labelArr)
    /* 判断options存在并且>10自己mock的数据删除 */
    const find = options.findIndex(item => item.label === e) // 修改了findIndex的回调函数
    if (find !== -1 && find > 9) {
      const newOptions = [...options]
      newOptions.splice(find, 1)
      setoptions([...newOptions])
    }
  }
  /* 添加 */
  const addCheckedValues = () => {
    if (checkedLabel.length === 10) {
      showMessage({
        content: '已达添加数量上限',
        type: 'warning'
      })
      return
    }
    /* 判断名称重复 */
    if (checkedLabel.includes(customMess)) {
      showMessage({
        content: '标签内容重复，请重新输入',
        type: 'warning'
      })
      setCustomMess('')
      return
    }
    let findNum = 1
    options.forEach(option => {
      if (option.label === customMess) {
        findNum = 2
      }
    })
    if (findNum != 1) {
      showMessage({
        content: '创建内容与AI推荐标签重复',
        type: 'warning'
      })
      return
    }
    fileLibBuriedEvent({
      page: '管理标签弹窗',
      event_name: '自定义创建标签【创建】按钮',
      data_id: id,
      detail: JSON.stringify({ 结果: '成功' })
    })
    setoptions([...options, { label: customMess, value: customMess, hid: 1 }])
    const newLabelArr = [...checkedLabel, customMess]
    setcheckedValues(newLabelArr)
    setcheckedLabel(newLabelArr)
    setCustomMess('')
    /* 更新父级数据 */
    updata([...options, { label: customMess, value: customMess, hid: 1 }], newLabelArr)
  }

  const caseLeft = () => {
    // const diasbledLabel = value => {
    //   let dis = true
    //   if (disNum === 0) {
    //     return false
    //   }
    //   if (checkedLabel.includes(value)) {
    //     dis = true
    //   } else {
    //     dis = false
    //   }
    //   return dis
    // }
    // const [disNum, setDisNum] = useState(0)
    return (
      <div className="tagDialog_case flexCol" style={{ borderTopRightRadius: '0', borderBottomRightRadius: '0' }}>
        <div className="flexRow flexRowJustBet" style={{ marginBottom: '15px' }}>
          <Segmented
            defaultValue={t('lib.Recommended_ai')}
            onChange={value => setAlignValue(value)}
            options={[t('lib.Recommended_ai'), t('lib.Custom')]}
            className="Segmented_font"
          />
          {/* 重新生成 */}
          {alignValue === t('lib.Recommended_ai') ? (
            <span
              className="tagDialog_case_again cursonCase"
              onClick={e => {
                // setDisNum(1)
                settagLoading(true)
                again()
              }}
            >
              {tagLoading ? (
                <>
                  <Spin size="small" />
                  生成中
                </>
              ) : (
                <span>{t('lib.again')}</span>
              )}
            </span>
          ) : null}
        </div>
        {/* ai推荐 自定义创建 */}
        <div className="caseOverFlowY_tagDialog">
          {alignValue === t('lib.Recommended_ai') ? (
            <>
              <Checkbox.Group
                value={checkedValues}
                className="flexCol"
                style={{ width: '100%' }}
                onChange={CheckonChange}
              >
                {options.map(item => (
                  <Checkbox
                    className="tagDialog_case_checkCol caseMarBot domOverflowEllip"
                    // disabled={diasbledLabel(item.value)}
                    value={item.value}
                    key={item.value + Math.round(Math.random() * 100000000)}
                  >
                    {item.label}
                  </Checkbox>
                ))}
              </Checkbox.Group>
              {options.length === 0 ? <Empty description={t('empty')} image={Empty.PRESENTED_IMAGE_SIMPLE} /> : null}
            </>
          ) : (
            <div className="flexRow CustomInput_case_edit">
              <CustomInput
                style={{ height: '38px' }}
                value={customMess}
                placeholder={t('lib.putMaxSize')}
                onChange={e => {
                  setCustomMess(e.target.value)
                }}
                maxLength={maxLength}
              ></CustomInput>
              <span
                className="customPutBut flexRow cursonCase"
                onClick={e => {
                  if (customMess.length < 2) {
                    showMessage({
                      content: t('lib.putMaxSize'),
                      type: 'warning'
                    })
                    fileLibBuriedEvent({
                      page: '管理标签弹窗',
                      event_name: '自定义创建标签【创建】按钮',
                      data_id: id,
                      detail: JSON.stringify({ 结果: '失败' })
                    })
                    return
                  }
                  addCheckedValues()
                }}
              >
                {t('create')}
              </span>
            </div>
          )}
        </div>
      </div>
    )
  }
  const caseRight = () => {
    return (
      <div
        className="tagDialog_case flexCol"
        style={{ borderTopLeftRadius: '0', borderBottomLeftRadius: '0', borderLeft: '0' }}
      >
        <div className="flexRow flexRowJustBet" style={{ marginBottom: '15px' }}>
          <span className="tagDialog_case_title">
            {t('lib.Selected')}
            <span className="tagDialog_case_title_num">（{checkedLabel.length}/10）</span>
          </span>
          {/* 占位case */}
          <span style={{ width: '10px', height: '34px' }}></span>
        </div>
        {checkedLabel.length === 0 ? (
          <Empty description={t('empty')} image={Empty.PRESENTED_IMAGE_SIMPLE} />
        ) : (
          <div className="caseOverFlowY">
            {Array.isArray(checkedLabel) &&
              checkedLabel?.map((value, index) => {
                return (
                  <div key={value} className="flexRow flexRowJustBet caseMarBot">
                    <span>{value}</span>
                    <svg
                      onClick={e => {
                        sliceCheckedValues(index, value)
                      }}
                      className="cursonCase"
                      width="16"
                      height="16"
                      viewBox="0 0 16 16"
                      fill="none"
                      xmlns="http://www.w3.org/2000/svg"
                    >
                      <path
                        d="M4 5V12C4 12.5523 4.44772 13 5 13H11C11.5523 13 12 12.5523 12 12V5"
                        stroke="#ADB8C3"
                        strokeLinecap="round"
                      />
                      <path d="M3 5H13" stroke="#ADB8C3" strokeLinecap="round" />
                      <path
                        d="M6 5V4C6 3.44772 6.44772 3 7 3H9C9.55228 3 10 3.44772 10 4V5"
                        stroke="#ADB8C3"
                        strokeLinecap="round"
                      />
                    </svg>
                  </div>
                )
              })}
          </div>
        )}
      </div>
    )
  }
  return (
    <ModalComponent
      title={title}
      width={640}
      content={
        <div className="flexCol">
          <span className="tagdialog_head_title">{t('lib.dialogHeadTitle')}</span>
          <div className="flexRowStart" style={{ marginTop: '12px', marginBottom: '8px' }}>
            {caseLeft()}
            {caseRight()}
          </div>
        </div>
      }
      okText={t('confirmButton')}
      cancelText={t('cancel')}
      onCancel={() => {
        cancel()
      }}
      onOk={() => {
        submit(checkedValues, checkedLabel)
      }}
    />
  )
}

export default TagDialog
